import { IBehaviour } from "./interface/IBehaviour";
import { EStatus } from "./common/EnumType";

export class BehaviorTree<T = any> {
    private _root: IBehaviour;
    private endCallback: Function = null;
    
    constructor(root?: IBehaviour) {
        if (root) {
            this._root = root;
        }
    }

    set root(t: IBehaviour) {
        this._root = t;
    }

    get root() {
        return this._root;
    }

    public setEndCallback(endCallback: Function) {
        this.endCallback = endCallback;
    }

    public tick(): void {
        try {
            let status = this._root.tick();
            if (status == EStatus.Success || status == EStatus.Failure) {
                this.reset();
                this.endCallback?.(status);
            }
        } catch (e) {
            console.error(e);
            this.reset();
            this.endCallback?.(EStatus.Failure);
        }
    }

    public haveRoot(): boolean {
        return this._root != null ? true : false;
    }

    public setRoot(inNode: IBehaviour): void {
        this._root = inNode;
    }

    public getRoot() {
        return this._root;
    }

    public release(): void {
        this._root.release();
    }

    public reset(): void {
        this._root.reset();
    }

}